#include "sm4.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include "crypto.h"
using namespace std;
//16进制数组转无符号字符数组
int hex_str2bytes(unsigned char *in ,  unsigned char *out , int *outLen)
{
    int i = 0 , j = 0;
    int num = 0;
    int tmp = 0;
    for (i = 0 ; i < strlen((char *)in) ; i++)
    {
        if(in[i] < 58 && in[i] > 47) //0-9
            tmp = in[i]-48;
        else if(in[i] < 71 && in[i] > 64) //A-F
            tmp = 10+in[i]-65;
        else if(in[i] < 103 && in[i] > 96) //a-f
            tmp = 10+in[i]-97;
        else
        {
            printf("Invalid arg!\n");
            return -1;
        }

        if(i%2 == 0)
            num = tmp*16;
        else
        {
            num += tmp;
            out[j++] = num;
        }
    }
    *outLen = j;
    return 0;
}

int main(int argc, char *argv[])
{
    Crypto::init(); // 初化随机种子 

// 模拟协商 
    Crypto client;  // A 
    size_t* g_p = client.get_public(); // 生成 (g, p) 
    size_t X = client.get_pub_key();   // 计算 X 

    Crypto server(g_p[0], g_p[1]);     // B, 接收 (g, p)  
    size_t Y = server.get_pub_key();   // 计算 Y 
    char* K2 = server.get_key(X);      // B 计算会话密钥 
    char* K1 = client.get_key(Y);      // A 通过 B 发的 Y 计算会话密钥 
    if (argc != 2)
    {
        printf("Usage: recver text[hex32]\n");
        return 0;
    }
    sm4_context ctx;
    int len = 0;
    unsigned char data[16] = { 0 };
    unsigned char output[17] = { 0 }; // 最后一位结束符
    hex_str2bytes((unsigned char *)argv[1], data, &len);
    sm4_setkey_dec(&ctx, (unsigned char *)K1);
    sm4_crypt_ecb(&ctx,
                  SM4_DECRYPT,
                  16,
                  data,
                  output);
    printf("%s\n", output);
    return 0;
}
